package com.glut.controller;


import java.io.*;
import java.sql.Blob;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.glut.service.ExaminationService;
import com.glut.service.GeneratePaperService;
import com.glut.service.LevKldService;
import com.glut.service.SdfsQuestionsService;
import com.glut.util.Constants;
import com.glut.util.Logable;
import com.glut.util.StringUtil;
import com.glut.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import static org.apache.commons.lang3.StringUtils.trim;

/**
 * @Author:shenly
 * @date:2020/05/03
 * @Description:
 */

@Controller
@RequestMapping(value = "/testPaper")
public class TestPaperController extends Logable {
    @Autowired
    private HttpSession session;

    @Autowired
    LevKldService levKldService;

    @Autowired
    ExaminationService examinationService;

    @Autowired
    SdfsQuestionsService sdfsQuestionsService;

    @Autowired
    GeneratePaperService generatePaperService;

    // 得到知识点信息
    @RequestMapping("/selectAllSecByLevID/{pageNum}")
    @ResponseBody
    public List<SecKld> selectAllSecKld(SecKld secKld,
                                        ModelMap modelMap,
                                        @PathVariable Integer pageNum,
                                        HttpSession session) {
        if(pageNum==null||pageNum< 1){
            // 保留查询条件
            session.setAttribute("secKldCondition",secKld);
            pageNum=1;
        }else{
            // 点击分页
            secKld = (SecKld)session.getAttribute("secKldCondition");
        }
        Page<SecKld> secKldList = (Page<SecKld>)levKldService.selectAllSecKld(secKld,pageNum,10);

        return secKldList;
    }

    // 得到各种题型的数量信息
    /*@RequestMapping(value = "/amount", method = RequestMethod.GET)
    @ResponseBody
    public Result getCountQuestionType() {
        Result result = new Result();
        List<Map<String, Object>> list = new LinkedList<>();
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();

        // 题型
        List<SdfsQuestions> qtList = sdfsQuestionsService.selectAllSdfsQuestions();
       // getQuestionByType()
        for (SdfsQuestions qt : qtList) {
            map1.put(qt.getSdfsQuestionID() + "_easy",
                    sdfsQuestionsService.countQuesByKpsAndQtAndDl(null, qt.getQuestionType(), 0.25));
            map1.put(qt.getSdfsQuestionID() + "_medium",
                    sdfsQuestionsService.countQuesByKpsAndQtAndDl(null,qt.getQuestionType(), 0.5));
            map1.put(qt.getSdfsQuestionID() + "_hard",
                    sdfsQuestionsService.countQuesByKpsAndQtAndDl(null,qt.getQuestionType(), 0.75));
            map2.put(qt.getSdfsQuestionID() + "", sdfsQuestionsService.countQuesByKpsAndQtAndDl(null, qt.getQuestionType(), null));
        }
        list.add(map1);
        list.add(map2);
        result.setList(list);
        result.setRtnCode("0");
        result.setRtnMessage("题目信息查询成功");
        return result;
    }*/

    // 得到各种题型的数量信息--增加知识点限制
   /* @RequestMapping(value = "/amount/", method = RequestMethod.POST)
    @ResponseBody
    public Result getQuesAmountBySIdAndQt(@RequestBody Map<String, Object> request) {
        Result result = new Result();
        List<String> kpsList = (List<String>) request.get("kps");
        // 进行分割查询二级知识点的ID
       *//* String[] s = secKld.split(",");
        for (int i = 0; i < kpsList.length; i++) {
            kpsList.add(s[i]);
        }*//*
        List<Map<String, Object>> list = new LinkedList<>();
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();

        // 题型
        List<SdfsQuestions> qtList = sdfsQuestionsService.selectAllSdfsQuestions();
        for (SdfsQuestions qt : qtList) {
            map1.put(qt.getSdfsQuestionID() + "_easy",
                    sdfsQuestionsService.countQuesByKpsAndQtAndDl(kpsList, qt.getQuestionType(), 0.25));
            map1.put(qt.getSdfsQuestionID() + "_medium",
                    sdfsQuestionsService.countQuesByKpsAndQtAndDl(kpsList,qt.getQuestionType(), 0.5));
            map1.put(qt.getSdfsQuestionID() + "_hard",
                    sdfsQuestionsService.countQuesByKpsAndQtAndDl(kpsList,qt.getQuestionType(), 0.75));
            map2.put(qt.getSdfsQuestionID() + "", sdfsQuestionsService.countQuesByKpsAndQtAndDl(kpsList, qt.getQuestionType(), null));
        }
        list.add(map1);
        list.add(map2);
        result.setList(list);
        result.setRtnCode("0");
        result.setRtnMessage("题目信息查询成功");
        return result;
    }*/

    //根据知识点+问题Id查出所有题目
    @RequestMapping(value="/getQuesBySIdAndKnowsAndQt",method=RequestMethod.POST)
    @ResponseBody
    public Result getQuesBySIdAndKnowsAndQt(@RequestBody Map<String, Object> request) {
        Result result=new Result();
        List<Map<String, String>> questionMapList=new ArrayList<>();//存放题目结果
        Map<String, Object> resultMap=new HashMap<>();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Integer qtId=null;
        List<String> kps=null;
        int pageNum,pageSize;
        int count;//题目的提取次数

        //前台信息
        if(request.get("qtId")!=null&&request.get("qtId")!="") {
            qtId=Integer.parseInt(request.get("qtId").toString());
        }
        kps= (List<String>) request.get("kps");

        if(request.get("pageNum")!=null&&request.get("pageNum")!="") {
            pageNum=Integer.parseInt(request.get("pageNum").toString());
        }else {
            pageNum=1;
        }
        if(request.get("pageSize")!=null&&request.get("pageSize")!="") {
            pageSize=Integer.parseInt(request.get("pageSize").toString());
        }else {
            pageSize=10;
        }
        System.out.println("pageNum   PageSize");
        System.out.println(pageNum);
        System.out.println(pageSize);

        //取出页面信息
        //PageHelper.startPage(pageNum, pageSize);

        //根据知识点+问题Id查出所有题目
        List<SdfsQuestions> questionsList=sdfsQuestionsService.checkAllQuesByKpsAndQtAndDl(kps,qtId,null,pageNum,pageSize);
        //将questionList转换成List<map<>>
        for(SdfsQuestions questions:questionsList) {
            Map<String, String> tempMap=new HashMap<>();
            if(questions.getSdfsQuestionID()!=null) {
                tempMap.put("qId", questions.getSdfsQuestionID().toString());

                //题目的抽取次数
                count= sdfsQuestionsService.countgetBy(questions.getSdfsQuestionID());
                tempMap.put("count", count+"");
            }
            if(questions.getQuestionType()!=null) {
                tempMap.put("questionTypeId", questions.getQuestionType().toString());
                //tempMap.put("questionTypeCN", sdfsQuestionsService.getQuestionTypeById(questions.getSdfsQuestionID()));
            }

            if(questions.getSecKld()!=null) {
                tempMap.put("konwledgePointId", questions.getSecKld().toString());
            }

            if(questions.getsQuestionDetail().getsCorrect()!=null) {
                tempMap.put("qAnswer", questions.getsQuestionDetail().getsCorrect());
            }


            if(questions.getDifficulty()!=null) {
                tempMap.put("qDifficultyLevel", questions.getDifficulty().toString());
                tempMap.put("qDifficultyLevelCN",Constants.getDiffLevelStrCN(questions.getDifficulty()));
                tempMap.put("qDiffocultyLevelEN", Constants.getDiffLevelStrEN(questions.getDifficulty()));
            }

            questionMapList.add(tempMap);
        }

        //分页的信息
        PageInfo<SdfsQuestions> page=new PageInfo<SdfsQuestions>(questionsList);
        //page中有所有的试题信息
        resultMap.put("page", page);

        resultMap.put("questionsList", questionMapList);

        result.setMap(resultMap);
        result.setRtnCode("9999");
        result.setRtnMessage("题目信息查询成功");
        return result;
    }

    //自动生成试卷
    @RequestMapping(value="/generatePaperAuto",method=RequestMethod.POST)
    @ResponseBody
    public Result generatePaperAuto(@RequestBody Map<String,Object> request,
                                                 HttpSession session) {
        Result result=new Result();
        List<Integer> qtList2=new ArrayList<>();//存储前台题型

        Double paperDiffLev=Double.parseDouble(request.get("paperDiffLev").toString());
        Integer totalScore=Integer.parseInt(request.get("totalScore").toString());

        List<String> kpsList = (List<String>) request.get("kps");//知识点的list--知识点不重复
        List<Long> kpsList1 = (List<Long>) request.get("kps");//知识点的list--知识点不重复

        List<Integer> qts = (List<Integer>)request.get("qtSet");

        Integer sQNum = Integer.parseInt(request.get("sQuestion").toString());
        Integer dQNum = Integer.parseInt(request.get("dQuestion").toString());
        Integer fQNum = Integer.parseInt(request.get("fQuestion").toString());
        Integer shQNum = Integer.parseInt(request.get("shQuestion").toString());
        Integer synQNum = Integer.parseInt(request.get("synQuestion").toString());

        totalScore = sQNum*2+dQNum*2+fQNum*3+shQNum*5+synQNum*5;

        //不允许知识点重复----hashSet根据值的hashCode值判断是否重复，放到HashMap中
        Set<String> kpsSet=new HashSet<>();
        for(int i=0;i<kpsList.size();i++) {
            kpsSet.add(kpsList.get(i).toString());
        }

        // 查询各个题型的题目并存放
        List<Map<String, Integer>> qtNumList = new ArrayList<>();
        List<Map<String, List<SdfsQuestions>>> qtList = new ArrayList<>();
        Map<String, Integer> qtNumMap = new HashMap<String,Integer>();
        Map<String, List<SdfsQuestions>> map = new HashMap<String,List<SdfsQuestions>>();
        List<SdfsQuestions> questionsDB = new ArrayList<>();
            if (sQNum!=0){
                List<SdfsQuestions> sQuestions = sdfsQuestionsService.selectAllSdfsQuestionsByType(1);
                questionsDB.addAll(sQuestions);
                map.put("1",sQuestions);
            }
            if (dQNum!=0){
                List<SdfsQuestions> dQuestions = sdfsQuestionsService.selectAllSdfsQuestionsByType(2);
                questionsDB.addAll(dQuestions);
                map.put("2",dQuestions);
            }
            if (fQNum!=0){
                List<SdfsQuestions> fQuestions = sdfsQuestionsService.selectAllSdfsQuestionsByType(3);
                questionsDB.addAll(fQuestions);
                map.put("3",fQuestions);
            }
            if (shQNum!=0){
                List<SdfsQuestions> shQuestions = sdfsQuestionsService.selectAllSdfsQuestionsByType(4);
                questionsDB.addAll(shQuestions);
                map.put("4",shQuestions);
            }
            if (synQNum!=0){
                List<SdfsQuestions> synQuestions = sdfsQuestionsService.selectAllSdfsQuestionsByType(5);
                questionsDB.addAll(synQuestions);
                map.put("5",synQuestions);
            }
        qtNumMap.put("1",sQNum);
        qtNumMap.put("2",dQNum);
        qtNumMap.put("3",fQNum);
        qtNumMap.put("4",shQNum);
        qtNumMap.put("5",synQNum);
        qtNumList.add(qtNumMap);
        qtList.add(map);

        //取出题库中的题目
        //List<SdfsQuestions> questionsDB=sdfsQuestionsService.checkAllQuesByKpsAndQtAndDl();
        //实例化期望的试卷信息
        TempExam expectedExam=new TempExam(StringUtil.seqGenerate(), totalScore, paperDiffLev, kpsSet,qtNumList);

        //遗传算法
        TempExam resultUnit= geneticAlgorithm(questionsDB,expectedExam,qtList);

        Long eId=StringUtil.seqGenerate();
        SstsUsers user=(SstsUsers) session.getAttribute("user");
        int paperTotalScore=resultUnit.getTotalScore();
        double paperDifficutty=resultUnit.getDifficultyLevel();
        List<String> qIdList=new ArrayList<>();//试卷所有试题Id
        List<String> sQIdList=new ArrayList<>();//试卷所有单选试题Id
        List<String> dQIdList=new ArrayList<>();//试卷所有判断试题Id
        List<String> fQIdList=new ArrayList<>();//试卷所有填空试题Id
        List<String> shQIdList=new ArrayList<>();//试卷所有简答综合试题Id

        for(SdfsQuestions questions:resultUnit.getQuestionList()) {
            qIdList.add(questions.getSdfsQuestionID());

            if (questions.getQuestionType()==1){
                sQIdList.add(questions.getSdfsQuestionID());
            }else if (questions.getQuestionType()==2){
                dQIdList.add(questions.getSdfsQuestionID());
            }else if (questions.getQuestionType()==3){
                fQIdList.add(questions.getSdfsQuestionID());
            }else if (questions.getQuestionType()==4||questions.getQuestionType()==5){
                shQIdList.add(questions.getSdfsQuestionID());
            }
        }

        List<SQuestionDetail> sQuestionDetailResult = new ArrayList<>();
        List<DQuestionDetail> dQuestionDetailResult = new ArrayList<>();
        List<FQuestionDetail> fQuestionDetailResult = new ArrayList<>();
        List<ShQuestionDetail> shQuestionDetailResult = new ArrayList<>();
        List<TempExam> resultUnitList=new ArrayList<>();//试卷所有简答综合试题Id


        // 返回试卷，根据题型分别查询，存入map里面返回页面
        // 单选题
        for (String s:sQIdList){
            SQuestionDetail sQuestionDetail = new SQuestionDetail();
            sQuestionDetail.setsQuestionID(s);
            sQuestionDetailResult.add(sdfsQuestionsService.selectSQuestionsByID(sQuestionDetail));

        }
        // 判断题
        for (String d:dQIdList){
            DQuestionDetail dQuestionDetail = new DQuestionDetail();
            dQuestionDetail.setdQuestionID(d);
            dQuestionDetailResult.add(sdfsQuestionsService.selectDQuestionsByID(dQuestionDetail));

        }
        // 填空题
        for (String f:fQIdList){
            FQuestionDetail fQuestionDetail = new FQuestionDetail();
            fQuestionDetail.setfQuestionID(f);
            FQuestionDetail fQuestionDetail1 = sdfsQuestionsService.selectFQuestionsByID(fQuestionDetail);
            fQuestionDetailResult.add(fQuestionDetail1);

        }
        // 简答综合题
        for (String sh:shQIdList){
            ShQuestionDetail shQuestionDetail = new ShQuestionDetail();
            shQuestionDetail.setShQuestionID(sh);
            shQuestionDetailResult.add(sdfsQuestionsService.selectShQuestionsByID(shQuestionDetail));

        }

        resultUnitList.add(resultUnit);
        // 存入session
        System.out.println(sQuestionDetailResult);
        session.setAttribute("sExamDetail",sQuestionDetailResult);
        session.setAttribute("dExamDetail",dQuestionDetailResult);
        session.setAttribute("fExamDetail",fQuestionDetailResult);
        session.setAttribute("shExamDetail",shQuestionDetailResult);
        session.setAttribute("resultUnit",resultUnitList);


        result.setRtnMessage("试卷生成成功，前往测试");
        result.setRtnCode("0");
        return result;

      /*  try {
            //TODO 将产生的最终试卷存入数据库--试卷

            if(!examinationService.inToDB(eId,user.getSstsUserID(),paperTotalScore,paperDifficuttyB,qIdListB,qtList)) {
                error("服务器崩溃，添加试卷信息失败，请重新尝试");
                result.setRtnMessage("服务器崩溃，添加试卷信息失败，请重新尝试");
                result.setRtnCode("-9999");
                return result ;
            }
        }catch(Exception e) {
            error("服务器崩溃，添加试卷信息失败，请重新尝试");
            result.setRtnMessage("服务器崩溃，添加试卷信息失败，请重新尝试");
            result.setRtnCode("-9999");
            //打印错误栈日志
            e.printStackTrace();
            return result ;
        }
*/
        //生成word文档
       /* try {
            if(!exportWord(eId)) {
                error("服务器崩溃，生成word格式失败，请重新尝试");
                result.setRtnMessage("服务器崩溃，生成word格式失败，请重新尝试");
                result.setRtnCode("-9999");
                return result;
            }

        } catch (IOException e) {
            e.printStackTrace();
            error("服务器崩溃，生成试卷word格式失败，请重新尝试");
            result.setRtnMessage("服务器崩溃，生成word格式失败，请重新尝试");
            result.setRtnCode("-9999");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            error("服务器崩溃，生成试卷word格式失败，请重新尝试");
            result.setRtnMessage("服务器崩溃，生成word格式失败，请重新尝试");
            result.setRtnCode("-9999");
            return result;
        }
*/


    }

    //根据试卷Id生成word
    //@RequestMapping(value="/exportWord/{eId}/{eType}",method=RequestMethod.GET)
    //return  true：生成word成功    false：失败
   /*public boolean exportWord(Long eId) throws IOException, TemplateException {
        String directoryName=Constants.WORD_TEMPLETE_DIRECTORY_NAME;
        Map<String,Object> resultMap=new HashMap<>();

        //模板存放的实际地址
        String t=request.getSession().getServletContext().getRealPath("");
        String realPath=t.substring(0, t.lastIndexOf('\\'))+"\\"+directoryName;
        System.out.println("wordTemplete_realPath:-------------"+realPath);

        //试题信息
        Examination exam=examinationService.get(eId);
        Long examNo=exam.getExamNo();
        Calendar calandar=Calendar.getInstance();
        int nowYear=calandar.get(Calendar.YEAR);
        int nowMonth=calandar.get(Calendar.MONTH);
        int semester,startYear=nowYear,stopYear=nowYear+1;
        if(nowMonth<9) {
            semester=1;
        }else {
            semester=2;
        }

        resultMap.put("examNo", examNo);
        resultMap.put("startYear", startYear);
        resultMap.put("stopYear", stopYear);
        resultMap.put("semester",semester);

        //题型个数--试题头部打分的表格--scoreThList   scoreList
        int eqtCount=eqtService.countByEId(eId);

        List<String> scoreThList=new ArrayList<>();
        scoreThList.add("序号");
        for(int i=1;i<=eqtCount;i++) {
            scoreThList.add(Constants.numGetChinese(i));
        }
        scoreThList.add("总分");
        resultMap.put("scoreThList", scoreThList);

        List<String> scoreList=new ArrayList<>();
        scoreList.add("得分");
        for(int i=1;i<=eqtCount;i++) {
            scoreList.add("");
        }
        scoreList.add("");
        resultMap.put("scoreList", scoreList);

        //写入所有题目
        //试卷题型信息--已经按照题型排列顺序排列
        List<ExamQuestiontype> eqtList= eqtService.allExamQuestiontypes(eId);
        List<Map<String,Object>> quesList=new ArrayList<>();
        List<Map<String, String>> answerList=new ArrayList<>();
        List<Map<String, Object>> question;
        Map<String, String> answer;
        StringBuilder tempAnswerContent;

        ExamQuestiontype tempEqt;//试卷中题型
        QuestionType tempQt;//题型实体
        List<SdfsQuestions> qList;//试题列表
        String tempContent;String tempImagesXmlHref;String tempImagesBase64;
        Map<String, Object> tmepResultMap=null;

        StringBuilder sb = new StringBuilder();
        StringBuilder imagesXmlHrefString=new StringBuilder();
        StringBuilder imagesBase64=new StringBuilder();
        Map<String, Object> tempQuestionMap;//临时存放问题详情Map
        Map<String, Object> tempMap;//临时存放试卷中所有题型

        for(int i=1;i<=eqtCount;i++) {
            question=new ArrayList<>();
            answer=new HashMap<>();
            tempAnswerContent=new StringBuilder();

            tempMap = new HashMap<>();
            tempEqt=eqtList.get(i-1);//当前试题类型
            tempQt=qtService.getQuestionTypeById(tempEqt.getQuestionTypeId().toString());

            qList=questionService.getQuestionsByEIdAndEQTId(eId, tempEqt.getQuestionTypeId(),eType);//当前试卷-题型下的题目（按照难易度排序）

            String title=Constants.numGetChinese(i)+"、"+tempQt.gettTitle()+"共"+qList.size()+"题，每题"+tempEqt.getTypeScore()+"分，共计"+qList.size()*tempEqt.getTypeScore()+"分";
            tempMap.put("title",title);
            answer.put("title", title);

            for(int j=1;j<=qList.size();j++) {
                tempQuestionMap=new HashMap<>();

                tempAnswerContent.append(j+"."+qList.get(j-1).getqAnswer());
                if(!qList.get(j-1).getqAnswer().contains("<p>")) {
                    tempAnswerContent.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                }
                //处理的图片信息（总）
                sb.append(qList.get(j-1).getqTitle());

                StringBuilder sbTemp=new StringBuilder();
                sbTemp.append(qList.get(j-1).getqTitle());

                //处理数据库中富文本
                tmepResultMap=getHandleredInfo(sbTemp);
                tempContent=tmepResultMap.get("docBodyBlock").toString();
                tempImagesXmlHref=tmepResultMap.get("imagesXmlHrefString").toString();
                tempImagesBase64=tmepResultMap.get("iamgebase64").toString();

                //所有的图片信息以及图片链接信息
                imagesXmlHrefString.append(tempImagesXmlHref);
                imagesBase64.append(tempImagesBase64);

                System.out.println("======tempContent==============");
                System.out.println(tempContent);
                //--绑定题目序号和题目
                String content=bindTitleAndNum(j+"",tempContent);
                tempQuestionMap.put("content",content);
                question.add(tempQuestionMap);
            }
            tempMap.put("question",question);
            quesList.add(tempMap);
            answer.put("content", tempAnswerContent.toString());
            answerList.add(answer);
        }

        resultMap.put("quesList", quesList);
        resultMap.put("answerList", answerList);

        //题型-题目-答案
//		contentMap.put("title","题目");
//		contentMap.put("question", "选择的是");
//		contentMap.put("answer", "答案");
//
//		resultMap.put("content", contentMap);


        //Map<String, Object> handlerMap=getHandleredInfo(sb);
        //String imagesBase64=handlerMap.get("iamgebase64").toString();
        //String imagesXmlHrefString=handlerMap.get("imagesXmlHrefString").toString();


        resultMap.put("imagesXmlHrefString",imagesXmlHrefString);
        resultMap.put("imagesBase64",imagesBase64);

        //Configuration用于读取ftl文件
        Configuration configuration=new Configuration();
        configuration.setDefaultEncoding("utf-8");

        configuration.setDirectoryForTemplateLoading(new File(realPath));

        File outFile=null;
        if(eType==0) {
            outFile=new File(realPath+"\\"+eId+"A.doc");
        }else if(eType==1) {
            outFile=new File(realPath+"\\"+eId+"B.doc");
        }

        //以utf-8编码读取ftl文件
        Template template=configuration.getTemplate("examTest.ftl","utf-8");

        Writer out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"),10240);

        template.process(resultMap, out);
        out.close();

        //将生成的word地址存入Exam中
        if(eType==0) {
            exam.seteAddressA("http://localhost:8080/wordTemplete/"+eId+"A.doc");
        }
        if(eType==1) {
            exam.seteAddressB("http://localhost:8080/wordTemplete/"+eId+"B.doc");
        }

        //更新
        if( examService.updateByPrimaryKey(exam)==1) {
            return true;
        }else {
            return false;
        }

    }
*/
    /*遗传算法
     * questionsDB题库
     * expectedExam：期望试题
     * TempExam resultUnit最终试题
     * */
    public TempExam geneticAlgorithm(List<SdfsQuestions> questionsDB,TempExam expectedExam,List<Map<String, List<SdfsQuestions>>> qtList) {
        //最终试题
        TempExam resultUnit=null,resultUnitTemp=null;

        //迭代次数计数器
        int count=1;

        //初始化种群
        List<TempExam> unitList=generatePaperService.initPol(20, expectedExam, questionsDB,qtList);
        resultUnitTemp=getMaxAdapterUnit(unitList);
        System.out.println("----------------遗传算法组卷---------------------------------------");
        System.out.println("初始种群-------------");
        showUnit(unitList);
        System.out.println("-----------------------开始迭代-------------------------");

        boolean flag=false;
        while(!generatePaperService.isEnd(unitList, Constants.EXPAND_ADATPER)) {
            System.out.println("在"+(count++)+"代未得到结果----------"+unitList.size()+"------------------");

            if(count>Constants.RUN_Count) {
                System.out.println("计算"+Constants.RUN_Count+"代仍没有结果，请重新设置条件");
                break;
            }

            //经过选择、交叉后种群数量只剩1或只剩0退出
            if(unitList.size()<=1) {
                System.out.println("没有结果");
                flag=true;
                break;
            }

            //选择--个数一定小于初始化种群
            unitList=generatePaperService.select(unitList, 5);

            //交叉
            unitList=generatePaperService.cross(unitList, 5, expectedExam,qtList);

            //判断是否可以结束
            if(generatePaperService.isEnd(unitList, Constants.EXPAND_ADATPER)) {
                break;
            }

            //变异
            unitList=generatePaperService.change(unitList, questionsDB, expectedExam,qtList);
        }

        if(count<=Constants.RUN_Count&&flag==false) {
            System.out.println("在第"+count+"代得到结果，结果为：**********************************");
            System.out.println("期望难度系数："+expectedExam.getDifficultyLevel());

            showResult(unitList,Constants.EXPAND_ADATPER);

            //如果有多个，取适应度最大的
            if(unitList.size()>=1) {
                resultUnit=getMaxAdapterUnit(unitList);
            }
        }else {
            //没有得到结果，取初始群种中适应度最大的
            resultUnit=resultUnitTemp;
        }

        //最终结果试题
        System.out.println("!!!!!!!!!!!!!!!!!!!!!最终试题！！！！！！！！！！！！！！！！！！！！！！！");
        if(resultUnit!=null) {
            System.out.println("试卷id："+resultUnit.geteId());
            System.out.println("题目数量\t知识点分布\t\t难度系数\t\t适应度");
            System.out.println(resultUnit.getQuestionList().size()+"\t"+resultUnit.getKpCoverage()+"\t"+resultUnit.getDifficultyLevel()+"\t"+resultUnit.getAdapterDegree());
        }

        return resultUnit;
    }



    //展示种群个体信息
    public void showUnit(List<TempExam> unitList) {
        for(TempExam unit:unitList) {
            System.out.println("编号\t\t\t知识点分布\t\t\t难度系数\t\t\t适应度");
            System.out.println(unit.geteId()+"\t"+unit.getKpCoverage()+"\t"+unit.getDifficultyLevel()+"\t"+unit.getAdapterDegree());
            List<String> quesIdList=new ArrayList<>();
            for(SdfsQuestions questions:unit.getQuestionList()) {
                quesIdList.add(questions.getSdfsQuestionID());
            }
            System.out.println("问题列表："+quesIdList);
            System.out.println();
            System.out.println();
        }

    }

    //展示结果
    public void showResult(List<TempExam> unitList,double expand) {
        for(TempExam unit:unitList) {
            if(unit.getAdapterDegree()>=expand) {
                System.out.println("试卷id："+unit.geteId());
                System.out.println("题目数量\t知识点分布\t\t难度系数\t\t适应度");
                System.out.println(unit.getQuestionList().size()+"\t"+unit.getKpCoverage()+"\t"+unit.getDifficultyLevel()+"\t"+unit.getAdapterDegree());
            }
        }
    }

    //适应度最大的种群个体
    public TempExam getMaxAdapterUnit(List<TempExam> unitLists) {
        TempExam maxUnit=new TempExam();
        for(TempExam unit:unitLists) {
            if(unit.getAdapterDegree()>=maxUnit.getAdapterDegree()) {
                maxUnit=unit;
            }
        }
        return maxUnit;
    }

    /**
     * 新增考卷
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/insertExam",method=RequestMethod.POST)
    @ResponseBody
    @Transactional
    public Map<String, Integer> insertExam(@RequestBody Map<String,Object> request,HttpSession session){

        Result result = new Result();

        // 获取用户id
        SstsUsers loginUser = (SstsUsers)session.getAttribute("loginUser");
        // 获取考卷题目
        List<SQuestionDetail> sExamDetail = (List<SQuestionDetail>)session.getAttribute("sExamDetail");
        List<DQuestionDetail> dExamDetail = (List<DQuestionDetail>)session.getAttribute("dExamDetail");
        List<FQuestionDetail> fExamDetail = (List<FQuestionDetail>)session.getAttribute("fExamDetail");
        List<ShQuestionDetail> shExamDetail = (List<ShQuestionDetail>)session.getAttribute("shExamDetail");
        List<TempExam> tempExam = (List<TempExam>)session.getAttribute("resultUnit");


        // 系统评单选判断答题分
        List<String> sExamList = (List<String>) request.get("sExamList");
        List<String> dExamList = (List<String>)request.get("dExamList");

        List<String> fExamList = (List<String>)request.get("fExamList");
        List<String> shExamList = (List<String>)request.get("shExamList");

        List<String> fExamImages = (List<String>)request.get("fExamImages");
        List<String> shExamImages = (List<String>)request.get("shExamImages");

        // 填空简答综合还未评分，考卷分数为-1，存入map中
        Map<String, Object> sdMap = new HashMap<>();
        Map<String, Object> fsMap = new HashMap<>();

        sdMap.put("t_exam_no", tempExam.get(0).geteId().toString());
        sdMap.put("t_user_id", loginUser.getSstsUserID());
        sdMap.put("t_total_scores", 0);
        sdMap.put("t_exam_date", new Date());
        sdMap.put("t_e_difficluty_level", tempExam.get(0).getDifficultyLevel());
        sdMap.put("t_total_values", tempExam.get(0).getTotalScore());
        sdMap.put("t_total_scores", 0);
        sdMap.put("t_result", 0);

        fsMap.put("t_exam_no", tempExam.get(0).geteId().toString());
        fsMap.put("t_user_id", loginUser.getSstsUserID());
        fsMap.put("t_total_scores", 0);
        fsMap.put("t_exam_date", new Date());
        fsMap.put("t_e_difficluty_level", tempExam.get(0).getDifficultyLevel());
        fsMap.put("t_total_values", tempExam.get(0).getTotalScore());
        fsMap.put("t_total_scores", 0);
        fsMap.put("t_result", 0);

        // 单选判断总分
        int sd_score = 0;
        for (int i=0;i<sExamDetail.size();i++){

            sdMap.put("t_sd_id", sExamDetail.get(i).getsQuestionID());
            // 单独存放答案
            sdMap.put("t_sd_answer", sExamList.get(i));
            String correct = sExamDetail.get(i).getsCorrect();
            String answer = sExamList.get(i);
            // 答案answer和corecct对比，如果相同就加2 单独算
            if (trim(correct).equals(answer)){
                sd_score+=2;
                sdMap.put("t_sd_score", 2);
            }else {
                sdMap.put("t_sd_score", 0);
            }
            sdMap.put("t_value", 2);
            examinationService.insertExam(sdMap);
        }
        for (int i=0;i<dExamDetail.size();i++){

            sdMap.put("t_sd_id", dExamDetail.get(i).getdQuestionID());
            // 单独存放
            sdMap.put("t_sd_answer", dExamList.get(i));
            String correct = dExamDetail.get(i).getdCorrect();
            String answer = dExamList.get(i);
            // 答案answer和corecct对比，如果相同就加2 单独算
            if (trim(correct).equals(answer)){
                sd_score+=2;
                sdMap.put("t_sd_score", 2);
            }else {
                sdMap.put("t_sd_score", 0);
            }
            sdMap.put("t_value", 2);
            examinationService.insertExam(sdMap);
        }
        for (int i=0;i<fExamDetail.size();i++){

             /* for (int k=0;k<imageSrc.size();k++){
                img+=imageSrc.get(i);
            }*///String htmlText = trim(getHtmlText(fExamList.get(i)));
            //List<String> imageSrc = getImageSrc(fExamList.get(i));
            StringBuffer img = new StringBuffer();

            String s = null;
           if (fExamImages!=null && fExamImages.size()!=0){
                s = fExamImages.get(0);
           }

           /*if (htmlText.contains("对齐")){
               htmlText=null;
           }*/
            fsMap.put("t_fs_id", fExamDetail.get(i).getfQuestionID());
            fsMap.put("t_fs_answer", fExamList.get(i));
            fsMap.put("t_fs_images",s);
            fsMap.put("t_fs_score", -1);
            fsMap.put("t_total_value", 2);
            examinationService.insertFsExam(fsMap);
        }
        for (int i=0;i<shExamDetail.size();i++){

          /*  String htmlText = trim(getHtmlText(shExamList.get(i)));
            List<String> imageSrc = getImageSrc(shExamList.get(i));
            StringBuffer img = new StringBuffer();*/

            String s = null;
            if (shExamImages!=null && shExamImages.size()!=0){
                s = shExamImages.get(0);
            }

           /* if (htmlText.contains("对齐")){
                htmlText=null;
            }*/
            fsMap.put("t_fs_id", shExamDetail.get(i).getShQuestionID());
            fsMap.put("t_fs_answer", shExamList.get(i));
            fsMap.put("t_fs_images",s);
            fsMap.put("t_fs_score", -1);
            fsMap.put("t_total_value", 5);
            examinationService.insertFsExam(fsMap);
        }

        Examination examination = new Examination();
        fsMap.put("t_exam_no", tempExam.get(0).geteId().toString());
        fsMap.put("t_user_id", loginUser.getSstsUserID());
        examination.setExamNo(tempExam.get(0).geteId());
        examination.setUserID(sdMap.get("t_user_id").toString());
        examination.setTotalScores(sd_score);
        // 进行更新客观题评分
        int updateExamination = 0;
        // 考卷的系统评分
        if (sd_score!=0){
             updateExamination = examinationService.updateExamination(examination);
        }


        // 查询并将答题数据存入session中
        List<SdAnswers> sdExamAnswer = new ArrayList<>();
        List<FsAnswers> fsExamAnswer = new ArrayList<>();

        for (int i=0;i<tempExam.size();i++){
            sdExamAnswer.addAll(examinationService.selectSdExamById(loginUser.getSstsUserID(), tempExam.get(i).geteId().toString()));
        }
        for (int i=0;i<tempExam.size();i++){

            fsExamAnswer.addAll(examinationService.selectFsExamById(loginUser.getSstsUserID(),tempExam.get(i).geteId().toString()));
            fsExamAnswer.addAll(examinationService.selectShExamById(loginUser.getSstsUserID(),tempExam.get(i).geteId().toString()));
        }
        session.setAttribute("sdExamAnswer",sdExamAnswer);
        session.setAttribute("fsExamAnswer",fsExamAnswer);


        // 将新增结果存入map中返回页面进行判断
        Map<String,Integer> map1 = new HashMap<String, Integer>();
        map1.put("insertExam",1);
        return map1;
    }

    /**
     * 截取html文本
     * @param strHtml
     * @return
     */
    public static String getHtmlText(String strHtml) {
        String txtcontent = strHtml.replaceAll("</?[^>]+>", ""); //剔出<html>的标签
        txtcontent = txtcontent.replaceAll("<p>\\s*|\t|\r|\n|&nbsp;|</p>", "");//去除字符串中的空格,回车,换行符,制表符
        return txtcontent;
    }
    /**
     * 截取html图片
     * @param
     * @return
     */
    public static List<String> getImageSrc(String htmlStr) {
        List<String> pics = new ArrayList<String>();
        String img = "";
        String a = "";
        Pattern p_image;
        Matcher m_image;
        //String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile
                (regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;
    }



    /**
     * 更新考卷--评分
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/updateExam",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, Integer> updateExam(@RequestBody Map<String,Object> request,HttpSession session){

        List<FQuestionDetail> fExamDetail = (List<FQuestionDetail>)session.getAttribute("fExamDetail");
        List<ShQuestionDetail> shExamDetail = (List<ShQuestionDetail>)session.getAttribute("shExamDetail");
        List<TempExam> tempExam = (List<TempExam>)session.getAttribute("resultUnit");

        // 答题列表
        List<String> fExamList = (List<String>)request.get("fExamList");
        List<String> shExamList = (List<String>)request.get("shExamList");

        // 客观题分数
        String totalScores = (String) request.get("totalScores");

        SstsUsers loginUser = (SstsUsers)session.getAttribute("loginUser");
        // 评分列表

        // 填空简答综合还未评分，考卷分数为-1，存入map中
        Map<String, Object> map = new HashMap<>();
        map.put("t_exam_no", tempExam.get(0).geteId().toString());
        map.put("t_user_id", loginUser.getSstsUserID());
        map.put("t_result", 0);

        int fsScores = 0;
        for (int i=0;i<fExamDetail.size();i++){
            map.put("t_fs_id", fExamDetail.get(i).getfQuestionID());
            fsScores=fsScores+(Integer.parseInt(fExamList.get(i)));
            map.put("t_total_scores", fsScores);
            map.put("t_fs_score", Integer.parseInt(fExamList.get(i)));
            examinationService.updateExam(map);
            map.replace("t_fs_id",null);
        }
        for (int i=0;i<shExamDetail.size();i++){
            map.put("t_fs_id", shExamDetail.get(i).getShQuestionID());
            fsScores=fsScores+(Integer.parseInt(shExamList.get(i)));
            map.put("t_total_scores", fsScores);
            map.put("t_fs_score", Integer.parseInt(shExamList.get(i)));
            examinationService.updateExam(map);
            map.replace("t_fs_id",null);
        }
        int totalScore = 0;
        if (StringUtils.isNotBlank(totalScores)){
             totalScore = (Integer.parseInt(totalScores));
        }
        fsScores=fsScores+totalScore;
        map.put("t_total_scores", fsScores);
        examinationService.updateExam(map);
        int updateExam = (int) map.get("t_result");
        // 查询并将答题数据存入session中
        List<SdAnswers> sdExamAnswer = new ArrayList<>();
        List<FsAnswers> fsExamAnswer = new ArrayList<>();

        for (int i=0;i<tempExam.size();i++){
            sdExamAnswer.addAll(examinationService.selectSdExamById(loginUser.getSstsUserID(), tempExam.get(i).geteId().toString()));
        }
        for (int i=0;i<tempExam.size();i++){

            fsExamAnswer.addAll(examinationService.selectFsExamById(loginUser.getSstsUserID(),tempExam.get(i).geteId().toString()));
            fsExamAnswer.addAll(examinationService.selectShExamById(loginUser.getSstsUserID(),tempExam.get(i).geteId().toString()));
        }
        session.setAttribute("sdExamAnswer",sdExamAnswer);
        session.setAttribute("fsExamAnswer",fsExamAnswer);

        // 将更新结果存入map中返回页面进行判断
        Map<String,Integer> map1 = new HashMap<String, Integer>();
        map1.put("updateExam",updateExam);
        return map1;
    }

    /**
     * 查询所有历史测试信息
     * @param
     * @return
     */
    @RequestMapping(value = "/selectAllHistoryExamByUserId/{sstsUserID}")
    public String selectAllHistoryExamByUserId(@PathVariable String sstsUserID,
                                               HttpSession session){

        // 根据用户id查询相应历史测试
        List<Examination> AllHistoryExamList = examinationService.selectAllExam(sstsUserID);
        System.out.println(AllHistoryExamList);

        session.setAttribute("AllHistoryExamList",AllHistoryExamList);

        return "redirect:/views/exam/allHistoryTest.jsp";
    }

    /**
     * 查询单个历史测试信息
     * @param session
     * @return
     */
    @RequestMapping(value = "/selectHistoryExam",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Integer> selectHistoryExam(String examNo, String userId,HttpSession session){

        // 根据用户id,试卷编号查询相应历史测试
        List<SdAnswers> sdHistoryExamList = examinationService.selectSdExamById(userId,examNo);
        List<FsAnswers> fsHistoryExamList = examinationService.selectFsExamById(userId,examNo);
        List<FsAnswers> shHistoryExamList = examinationService.selectShExamById(userId, examNo);


        session.setAttribute("sdHistoryExamList",sdHistoryExamList);
        session.setAttribute("fsHistoryExamList",fsHistoryExamList);
        session.setAttribute("shHistoryExamList",shHistoryExamList);

        Map<String,Integer> map1 = new HashMap<String, Integer>();
        map1.put("selectExam",1);

        return map1;
    }


}
